package app.dws;

import Bean.TradePaymentWindowBean;
import app.dwd.BaseAppV1;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import common.Constant;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import util.AtguiguUtil;
import util.FlinkSinkUtil;

import java.time.Duration;

/**
 * @author cheng
 * @create 2022-10-27 9:56
 */
public class Dws_DwsTradePaymentSucWindow extends BaseAppV1 {

    public static void main(String[] args) {
        new Dws_DwsTradePaymentSucWindow().init(4012,
                2,
                "Dws_DwsTradePaymentSucWindow",
                Constant.TOPIC_DWD_TRADE_PAY_DETAIL_SUC);
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        stream.map(key -> JSON.parseObject(key))
                .assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner((obj,ts) -> obj.getLong("ts") * 1000))

                .keyBy(obj -> obj.getString("user_id"))
                .process(new KeyedProcessFunction<String, JSONObject, TradePaymentWindowBean>() {

                    private ValueState<String> lastPayDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        lastPayDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastPayDateState", String.class));
                    }

                    @Override
                    public void processElement(JSONObject jsonObject, Context context, Collector<TradePaymentWindowBean> collector) throws Exception {

                        long ts = jsonObject.getLong("ts") * 1000;
                        String today = AtguiguUtil.toDate(ts);
                        String lastPayDate = lastPayDateState.value();
                        long puuC = 0L;
                        long pnuC = 0L;

                        if (!today.equals(lastPayDate)) {
                            lastPayDateState.update(today);
                            puuC = 1L;
                            if (lastPayDate == null) {
                                pnuC = 1L;
                            }
                        }

                        if (puuC == 1) {
                            TradePaymentWindowBean bean = new TradePaymentWindowBean("", "",
                                    puuC, pnuC,
                                    ts
                            );

                            collector.collect(bean);
                        }


                    }
                })
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(
                        new ReduceFunction<TradePaymentWindowBean>() {
                            @Override
                            public TradePaymentWindowBean reduce(TradePaymentWindowBean value1,
                                                                 TradePaymentWindowBean value2) throws Exception {
                                value1.setPaymentSucUniqueUserCount(value1.getPaymentSucUniqueUserCount() + value2.getPaymentSucUniqueUserCount());
                                value1.setPaymentSucNewUserCount(value1.getPaymentSucNewUserCount() + value2.getPaymentSucNewUserCount());
                                return value1;
                            }
                        },
                        new ProcessAllWindowFunction<TradePaymentWindowBean, TradePaymentWindowBean, TimeWindow>() {
                            @Override
                            public void process(Context ctx,
                                                Iterable<TradePaymentWindowBean> elements,
                                                Collector<TradePaymentWindowBean> out) throws Exception {

                                TradePaymentWindowBean bean = elements.iterator().next();
                                bean.setStt(AtguiguUtil.toDatTime(ctx.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDatTime(ctx.window().getEnd()));

                                bean.setTs(System.currentTimeMillis());
                                out.collect(bean);
                            }
                        }
                )
                .addSink(FlinkSinkUtil.getClickHouseSink("dws_trade_payment_suc_window", TradePaymentWindowBean.class));


    }
}
